/**
 * Created by lihao on 2017/3/7.
 */
//接口服务
"use strict";
var Promise = require('bluebird');
var api = require('../etc/api');

module.exports = function () {
    var PromiseTask = [];
    return {
        postApi: function (name, params) {
            var PromiseHttp = new Promise(function (resolve, reject) {
                $.ajax({
                    method: 'post',
                    url: api[name],
                    data: params,
                    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                    traditional: true,
                    success: function (data) {
                        resolve(data);
                    }

                    ,
                    error: function (err) {
                        reject(err);
                    }
                })
                ;
            });
            return PromiseHttp;
        },
        getApi: function (name, params) {
            var PromiseHttp = new Promise(function (resolve, reject) {
                $.ajax({
                    method: 'get',
                    url: api[name],
                    data: params,
                    // traditional: true,
                    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                    success: function (data) {
                        resolve(data);
                    },
                    error: function (err) {
                        reject(err);
                    }
                });
            });
            return PromiseHttp;
        },
        getTaskList: function () {
            return PromiseTask;
        },
        addTaskList: function (Task) {
            var _this = this;
            return new Promise(function (resolve, reject) {
                $('body').on('userIsLoad', function () {
                    Promise.map(Task, function (item) {
                        return new Promise(function (resolve2, reject2) {
                            _this.postApi(item.name, item.params)
                                .then(_this.error)
                                .then(function (data) {
                                    PromiseTask.push({name: item.name, fn: data});
                                    resolve2();
                                })
                                .catch(function (error) {
                                    reject2(error);
                                })
                        });
                    })
                        .then(function (data) {
                            resolve(data);
                        })
                        .catch(function (error) {
                            reject(error)
                        })
                });

            });

        },
        cleanTaskList: function () {
            PromiseTask = []
        },
        doTaskList: function () {
            var _this = this;
            return new Promise(function (resolve, reject) {
                Promise.map(PromiseTask, function (item) {
                    return Promise.resolve({
                        name: item.name,
                        data: item.fn
                    });
                }).then(function (data) {
                    var fn = function (r, n) {
                        r[n.name] = n.data;
                    };
                    resolve(_.transform(data, fn, {}));
                });

            });
        },
        getUrlParams: function (name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) return decodeURI(r[2]);
            return null;
        },
        getParams: function () {
            return _.chain(window.location.search)
                .thru(function (str) {
                    return _.transform((str.replace(/^\?/, '').split('&')), function (result, n) {
                        if (!_.isEmpty(n)) {
                            var param = n.split('=');
                            var temp = {};
                            temp[eval('"' + param[0] + '"')] = decodeURIComponent(param[1]);
                            result = _.extend(result, temp);
                        }
                        return !_.isEmpty(n);
                    }, {});
                })
                .value();
        },
        serialize: function (dom) {
            var fnForm = function (r, el) {
                if (!_.isEmpty(el.name)) r[el.name] = el.value;
            };
            var formData = _.map(dom, function (el) {
                return {
                    name: $(el).attr('name'),
                    value: $(el).val(),
                };
            });
            return _.transform(formData, fnForm, {});
        },
        error: function (data) {
            if (_.isObject(data)) {
                var msg;
                switch (data.code) {
                    case '1':
                    case 1:
                        return Promise.resolve(data);
                        break;
                    case -2:
                        return new Promise(function (resolve, reject) {
                            msg = '无访问权限';
                            if (_.has(data, 'message') && data.message != '') {
                                msg = data.message;
                            }
                            layer.msg(msg, {
                                time: 1500 //2秒关闭（如果不配置，默认是3秒）
                            }, function (layer) {
                                //do something
                                window.location.href = '/';
                                reject(new Error(msg));
                            });
                        });
                        break;
                    case 0:
                    case -1:
                    default:
                        return new Promise(function (resolve, reject) {
                            msg = '接口错误';
                            if (_.has(data, 'message') && data.message != '') {
                                msg = data.message;
                            }
                            layer.msg(msg, {
                                time: 1500 //2秒关闭（如果不配置，默认是3秒）
                            }, function (layer) {
                                //do something
                                reject(new Error(msg));
                            });
                        });

                }
            } else {
                return Promise.resolve(data);
            }
        },
        errorNoMsg: function (data) {
            if (_.isObject(data)) {
                var msg;
                switch (data.code) {
                    case '1':
                    case 1:
                        return Promise.resolve(data);
                        break;
                    case -2:
                        return new Promise(function (resolve, reject) {
                            msg = '无访问权限';
                            if (_.has(data, 'message') && data.message != '') {
                                msg = data.message;
                            }
                            layer.msg(msg, {
                                time: 1500 //2秒关闭（如果不配置，默认是3秒）
                            }, function (layer) {
                                //do something
                                window.location.href = '/';
                                reject(new Error(msg));
                            });
                        });
                        break;
                    case 0:
                    case -1:
                    default:
                        return new Promise(function (resolve, reject) {
                            msg = '接口错误';
                            if (_.has(data, 'message') && data.message != '') {
                                msg = data.message;
                            }
                            reject(new Error(msg));
                        });

                }
            } else {
                return Promise.resolve(data);
            }
        },
        toDate: function (str) {
            Date.prototype.toLocaleString = function () {
                return this.getFullYear() + "-" + (this.getMonth() + 1) + "-" + this.getDate();
            };
            var unixTimestamp = new Date(str);
            return unixTimestamp.toLocaleString();
        },
        //去千分位
        delCommafy: function (num) {
            if ((num + "").trim() == "") {
                return "";
            }
            num = num.replace(/,/gi, '');
            return num;
        },
        setCookie: function (name, value) {
            var Days = 30;
            var exp = new Date();
            exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
            document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString();
        },
        getCookie: function (name) {
            var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
            if (arr = document.cookie.match(reg))
                return unescape(arr[2]);
            else
                return null;
        },
        delCookie: function (name) {
            var exp = new Date();
            exp.setTime(exp.getTime() - 1);
            var cval = getCookie(name);
            if (cval != null)
                document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
        }
    }
}();
